package com.ktjy.action.aop;

import com.ktjy.aop.LoggerAspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Random;

@Aspect
@Component
public class PrinterAspect {
    private static Logger log = LoggerFactory.getLogger(LoggerAspect.class);

    @Pointcut("execution(* com.ktjy.action.printer.Printer.print(..))")
    public void printPointcut() {}
    /**
     * 前置增强 -打印进入方法和参数
     */
    @Before("printPointcut()")
    public void before(JoinPoint jp) {
        log.info("[PrinterAspect 前置增强] 正在调用{}的{}方法进行自检.....", jp.getTarget(), jp.getSignature().getName());
        // 创建 Random 对象
        Random random = new Random();
        int randomNumber = random.nextInt(10);
        if (randomNumber > 5) {
            log.info("[PrinterAspect 前置增强] 正在调用{}的{}方法进行自检.....打印机异常{},请修复后使用", jp.getTarget(), jp.getSignature().getName(), randomNumber);
            throw new RuntimeException("打印机异常,请修复后使用");
        }
        log.info("自检成功,打印机正常,开始打印......");
    }

    /**
     * 返回后增强 -打印方法返回值
     */
    @AfterReturning(value = "printPointcut()", returning = "result")
    public void afterReturning(JoinPoint jp, Object result) {
        log.info("[PrinterAspect 返回后增强] 正在调用{}的{}方法---->打印完成", jp.getTarget(), jp.getSignature().getName());
    }

    /**
     * 异常抛出增强
     */
    @AfterThrowing(value = "printPointcut()" , throwing = "e")
    public void afterThrowing(JoinPoint jp, Throwable e) {
        log.info("[PrinterAspect 异常抛出增强] 正在调用{}的{}方法---->打印失败,异常信息为:{}", jp.getTarget(), jp.getSignature().getName(), e.getMessage());
    }

}
